package com.elive.service.impl;

import com.elive.common.Const;
import com.elive.common.ServerResponse;
import com.elive.dao.LabelMapper;
import com.elive.dao.UserLabelMapper;
import com.elive.dao.UserMapper;
import com.elive.pojo.Label;
import com.elive.pojo.User;
import com.elive.pojo.UserLabel;
import com.elive.service.IUserService;
import com.elive.util.MD5Util;
import com.elive.vo.UserInfoVo;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wuyin on 2018/3/6.
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private UserLabelMapper userLabelMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {


        int resultCount = userMapper.checkUserName(username);


        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("该用户名不存在");
        }

        //MD5加密密码
        String md5Password = MD5Util.MD5EncodeUtf8(password);

        User user = userMapper.selectLogin(username,md5Password);


        if(user == null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
        // 对密码进行处理 将密码置为空
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功", user);
    }

    @Override
    public ServerResponse<User> customerLogin(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if(user != null){
            return ServerResponse.createBySuccess("登录微信小程序成功", user);
        }
        return ServerResponse.createByErrorMessage("登录失败，无此用户");
    }

    @Override
    public ServerResponse<String> register(User user) {
        // 用户名的校验
        ServerResponse validResponse = this.checkValid(user.getUsername(),"username");
        if(!validResponse.isSuccess()){
            return validResponse;
        }


        // 身份证号码的校验
        validResponse = this.checkValid(user.getIdNumber(),"idNumber");
        if(!validResponse.isSuccess()){
            return validResponse;
        }

        // 手机号的校验
        validResponse = this.checkValid(user.getPhone(),"phone");
        if(!validResponse.isSuccess()){
            return validResponse;
        }

        // 邮箱的校验
        validResponse = this.checkValid(user.getEmail(),"email");
        if(!validResponse.isSuccess()){
            return validResponse;
        }

        // 将用户角色设为房主
        user.setRole(Const.Role.ROLE_HOST);

        //MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));

        int resultCount = userMapper.insertSelective(user);

        if(resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");

    }

    @Override
    public ServerResponse<User> registerCustomer(User user) {
        // 用户名的校验
        ServerResponse validResponse = this.checkValid(user.getUsername(),"username");
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        // 将用户角色设为消费者
        user.setRole(Const.Role.ROLE_CUSTOMER);
        int resultCount = userMapper.insertSelective(user);
        Integer userId = user.getId();
        User registeredUser = userMapper.selectByPrimaryKey(userId);
        if(resultCount > 0 && registeredUser != null){
            return ServerResponse.createBySuccess("注册微信端用户成功",registeredUser);
        }
        return ServerResponse.createByErrorMessage("注册微信端用户失败");
    }

    public ServerResponse<String> checkValid(String str, String type){
        if(StringUtils.isNotBlank(type)){
            // 开始校验

            // 用户名的校验
            if(Const.USERNAME.equals(type)){
                int resultCount = userMapper.checkUserName(str);
                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }


            // 手机号的校验
            else if(Const.PHONE.equals(type)){
                String phoneRegex = "^1[3|4|5|7|8][0-9]\\d{4,8}$";
                if(!str.matches(phoneRegex)){
                    return ServerResponse.createByErrorMessage("手机格式错误");
                }
                int resultCount = userMapper.checkPhone(str);
                if(resultCount > 0){
                    return ServerResponse.createByErrorMessage("手机号已存在");
                }

            }

            // 身份证号码的校验
            else if(Const.IDNUMBER.equals(type)){
                int resultCount = userMapper.checkIdNumber(str);
                if(resultCount > 0){
                    return ServerResponse.createByErrorMessage("身份证已存在");
                }
            }

            // 邮箱的校验
            else if(Const.EMAIL.equals(type)){
                String emailRegex =  "\\w+(\\.\\w)*@\\w+(\\.\\w{2,3}){1,3}";
                if(!str.matches(emailRegex)){
                    return ServerResponse.createByErrorMessage("email格式错误");
                }
            }


        }else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    @Override
    public ServerResponse<String> updateUser(User user, String labels){

        int resultCount = userMapper.updateByPrimaryKeySelective(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("更新失败");
        }

        userLabelMapper.deleteByHostId(user.getId());

        if(labels != null){
            String [] labelList = labels.split(",");
            for(String label: labelList){
                resultCount = labelMapper.checkLabel(label);
                if(resultCount == 0){
                    // 无此标签
                    Label newLabel = new Label();
                    newLabel.setLabel(label);
                    int insertLabelResult = labelMapper.insert(newLabel);
                    if(insertLabelResult == 0){
                        return  ServerResponse.createByErrorMessage("标签更新失败");
                    }
                }
                Integer labelId = labelMapper.getIdByLabel(label);
                if(labelId != null){
                    UserLabel userLabel = new UserLabel();
                    userLabel.setHostId(user.getId());
                    userLabel.setLabelId(labelId);
                    int insertUserLable =  userLabelMapper.insert(userLabel);
                    if(insertUserLable == 0){
                        return ServerResponse.createByErrorMessage("标签更新失败");
                    }
                }
            }
        }
        return ServerResponse.createBySuccessMessage("更新成功");

    }

    @Override
    public ServerResponse<String> updateCustomerUser(User user) {
        int resultCount = userMapper.updateByPrimaryKeySelective(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("更新失败");
        }
        return ServerResponse.createBySuccessMessage("更新成功");

    }

    @Override
    public ServerResponse<UserInfoVo> getUserInfo(Integer userId) {
        if(userId == null){
            return ServerResponse.createByErrorMessage("用户未登录，请先登录");
        }
        // 获取user
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        List<Label> labelList = new ArrayList<Label>();


        //获取 labelIdList
        List<Integer> labelIdList = userLabelMapper.selectByUserId(userId);
        if(labelIdList.size() != 0){
            for(Integer labelId :labelIdList){
                Label label = labelMapper.selectByPrimaryKey(labelId);
                labelList.add(label);
            }
        }

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUserId(user.getId());
        userInfoVo.setUsername(user.getUsername());
        userInfoVo.setIdNumber(user.getIdNumber());
        userInfoVo.setPhone(user.getPhone());
        userInfoVo.setEmail(user.getEmail());
        userInfoVo.setImage(user.getImage());
        userInfoVo.setLabelList(labelList);


        return ServerResponse.createBySuccess("成功", userInfoVo);
    }

    @Override
    public ServerResponse<String> resetPassword(String oldPassword, String newPassword, User user) {
        System.out.println(oldPassword);
        System.out.println(user.getId()+"__________");
        System.out.println(MD5Util.MD5EncodeUtf8(oldPassword));
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(oldPassword), user.getId());
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(newPassword));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }else {
            return ServerResponse.createBySuccessMessage("密码更新失败");
        }
    }

    @Override
    public ServerResponse<User> isRegister(String username) {
        if(username != null){
            int count = userMapper.checkUserName(username);
            User  user;
            if(count > 0){
                user = userMapper.selectUserByUserName(username);
            }else {
                user = new User();
            }
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("");
    }


}
